<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>

      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="(tm, i) in tradeMarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          v-model="spu.description"
          placeholder="SPU描述"
          rows="5"
        ></el-input>
      </el-form-item>

      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handlerSuccess"
          :file-list="spuImageList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有${unSelectSaleAttr.length}个未选择`"
          v-model="attrIdAndattrName"
        >
          <el-option
            :label="unSelect.name"
            :value="`${unSelect.id}:${unSelect.name}`"
            v-for="(unSelect, i) in unSelectSaleAttr"
          ></el-option>
        </el-select>

        <el-button
          type="primary"
          iocn="el-icon-plus"
          :disabled="!attrIdAndattrName"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >

        <el-table border style="width: 100%" :data="spu.spuSaleAttrList">
          <el-table-column label="序号" width="80" aling="center" type="index">
          </el-table-column>
          <el-table-column label="销售属性" prop="saleAttrName" width="180"> </el-table-column>
          <el-table-column label="属性值名称及列表" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag
                :key="sale.id"
                v-for="(sale,index) in row.spuSaleAttrValueList"
                closable
                @close="row.spuSaleAttrValueList.splice(index,1)"
                :disable-transitions="false"
                style="margin: 0px 5px"
              >
                {{ sale.saleAttrValueName }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                @blur="handleInputConfirm(row)"
                ref="saveTagInput"
                size="small"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180">
            <template slot-scope="{row,$index}">
              <el-button type="danger" icon="el-icon-delete" @click="spu.spuSaleAttrList.splice($index,1)"></el-button>  
            </template>
            
          </el-table-column>  
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      attrIdAndattrName: null, //未选择的id
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      spu: {
        //三级分类id
        category3Id: 0,
        //描述
        description: "",
        id: 0,
        //spu图片信息
        spuImageList: [
          {
            id: 0,
            imgName: "",
            imgUrl: "",
            spuId: 0,
          },
        ],
        //spu名称
        spuName: "",
        //平台属性与属性值
        spuSaleAttrList: [
          {
            baseSaleAttrId: 0,
            id: 0,
            saleAttrName: "",
            spuId: 0,
            spuSaleAttrValueList: [
              {
                baseSaleAttrId: 0,
                id: 0,
                isChecked: "",
                saleAttrName: "",
                saleAttrValueName: "",
                spuId: 0,
              },
            ],
          },
        ],
        //平台id
        tmId: "",
      }, //存储spu信息属性
      tradeMarkList: [], //品牌信息
      spuImageList: [], //spu图片
      saleAttr: [], //全平台销售属性
    };
  },
  methods: {
    //删除图片的回调
    handleRemove(file, fileList) {
      this.spuImageList = fileList;
    },
    //预览图片的回调
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //添加图片回调
    handlerSuccess(response, file, fileList) {
      this.spuImageList = fileList;
    },
    //初始化spu数据
    async initspuData(spu) {
      //获取spu信息
      let spuResult = await this.$API.spu.reqSpuInfo(spu.id);
      if (spuResult.code === 200) {
        this.spu = spuResult.data;
      }

      //获取品牌信息
      let tradeMarkResult = await this.$API.spu.reqTradeMark();
      if (tradeMarkResult.code === 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }

      //获取spu图标
      let spuImageResult = await this.$API.spu.reqSpuImage(spu.id);
      if (spuImageResult.code === 200) {
        let listArr = spuImageResult.data;
        listArr.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        this.spuImageList = listArr;
      }

      //获取全平台的销售属性
      let baseSaleAttr = await this.$API.spu.reqBaseSaleAttr();
      if (baseSaleAttr.code===200) {
        this.saleAttr = baseSaleAttr.data;
      }
      
    },
    //添加销售属性
    addSaleAttr() {
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndattrName.split(":");
      //向SPU对象的spuSaleAttrList属性里面添加新的销售属性
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      //添加新的销售属性
      this.spu.spuSaleAttrList.push(newSaleAttr);
      //清空数据
      this.attrIdAndattrName = "";
    },
    //取消
    cancel() {
      //取消按钮的回调，通知父亲切换场景为0
      this.$emit("changeScene", 0);
      //清理数据
      //Object.assign:es6中新增的方法可以合并对象
      //组件实例this._data,可以操作data当中响应式数据
      //this.$options可以获取配置对象，配置对象的data函数执行，返回的响应式数据为空的
      Object.assign(this._data, this.$options.data());
    },
    //添加销售属性值
    addSaleAttrValue(row){
      //挂载在销售属性身上的响应式数据inputVisible，控制button与input切换
      this.$set(row, "inputVisible", true);
      //通过响应式数据inputValue字段收集新增的销售属性值
      this.$set(row, "inputValue", "");
    },
    //当el-input失去焦点时的回调
    handleInputConfirm(row){
      //解构出销售属性当中收集数据
      const { baseSaleAttrId, inputValue } = row;
      //新增的销售属性值的名称不能为空
      if (inputValue.trim() == "") {
        this.$message("属性值不能为空");
        return;
      }
      //属性值不能重复,这里也可以用some
      let result = row.spuSaleAttrValueList.every(
        (item) => item.saleAttrValueName != inputValue
      );
      if (!result) return;
      //新增的销售属性值
      let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue };
      //新增
      row.spuSaleAttrValueList.push(newSaleAttrValue);
      //修改inputVisible为false，不就显示button
      row.inputVisible = false;
    },
    //保存或添加 保存修改
    async saveOrUpdateSpu(){
      //整理数据
      this.spu.spuImageList=this.spuImageList.map(item=>{
        return {
          imgName:item.name,
          imgUrl:(item.response&&item.response.data)||item.imgUrl
        }
      })

      let result =await this.$API.spu.reqSaveOrUpdateSpu(this.spu)
      if (result.code===200) {
        this.$message({ type: "success", message: "保存成功" });
        //通知父组件回到场景0
        this.$emit("changeScene", {
          scene: 0,
          flag: this.spu.id ? "修改" : "添加",
        });
      } else {
        this.$message.error(result.data)
      }
      

      this.cancel()
    },
    //添加spu
    async addSpuData(category3Id){
      this.spu.category3Id=category3Id

      let tradeMarkResult = await this.$API.spu.reqTradeMark();
      if (tradeMarkResult.code === 200) {
        this.tradeMarkList = tradeMarkResult.data;
      };
      //获取全平台的销售属性
      let baseSaleAttr = await this.$API.spu.reqBaseSaleAttr();
      if (baseSaleAttr.code===200) {
        this.saleAttr = baseSaleAttr.data;
      }
    }
  },
  computed: {
    //计算出还未选择的销售属性
    unSelectSaleAttr() {
      //整个平台的销售属性一共三个：尺寸、颜色、版本 ----saleAttrList
      //当前SPU拥有的属于自己的销售属性SPU.spuSaleAttrList  ----颜色
      //数组的过滤方法，可以从已有的数组当中过滤出用户需要的元素，并未返回一个新的数据
      let result = this.saleAttr.filter((item) => {
        //every数组的方法，会返回一个布尔值【真，假的】
        return this.spu.spuSaleAttrList.every((item1) => {
          return item.name != item1.saleAttrName;
        });
      });
      return result;
    },
  },
};
</script>
